import {ensureLeadingSlash, isEmpty, removeExtraSlashes} from "../utils/Z.ts";
import React, {lazy} from "react";
interface MenuItemType {
    path?: string;
    hidden?: boolean;
    component?: string;
    meta?: {
        title: string;
        icon: string;
        noCache: boolean;
        link: string | null;
    };
    children?: MenuItemType[];
}

//处理路由数据，所有的都处于唯一一个子集，目前没有说页面再次嵌套三级路由子页面的说法
export const addRouteToMenu = (menuData: MenuItemType[], parentData: MenuItemType = {}): any[] => {
    let temp: any[] = [];
    menuData.forEach((menu) => {
        if (menu.component !== 'Layout') {
            const path = parentData.path ? `${ensureLeadingSlash(parentData.path)}${ensureLeadingSlash(menu.path)}` : `${ensureLeadingSlash(menu.path)}`;
            const rout = {
                path: removeExtraSlashes(path),
                element: WithLoadingComponent(menu.component)
            };
            // console.log(rout.path,  'menu.component');
            temp.push(rout);
        }
        if (menu.children) {
            // 确保传递正确的 parentData
            const result = addRouteToMenu(menu.children, { ...parentData, path: ensureLeadingSlash(parentData.path ? `${parentData.path}/${menu.path}` : `/${menu.path}`) });
            temp = temp.concat(result);
        }
    });
    return temp;
};



// 路由懒加载
export const WithLoadingComponent :React.FC = (path:any) => {
    const context:any = import.meta.glob('/src/views/**/*.tsx');// 使用 import.meta.glob 时递归查找,views文件夹下的所有的目录
    // lazy懒加载,需要异步函数
    // console.log(context[`/src/views/${path}.tsx`],path,'context')
    const Comp = lazy(() => {
        return new Promise((resolve) => {
            // importFn是一个函数
            const importFn = context[`/src/views/${path}.tsx`] || context['/src/views/404.tsx'];
            importFn().then((res:any) => resolve(res))
                .catch(() => {
                    resolve(context['/src/views/404.tsx']())
                })
        })
    })
    return (<React.Suspense fallback={<div> Loading...</div>}>
        <Comp/>
    </React.Suspense>)
}
